<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/20
 * Time: 15:08
 */

namespace App\CronTask;

use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\HttpClient\HttpClient;

/**
 * 更新已经结束比赛的赔率
 * Class BetCron
 * @package App\CronTask
 */
class BetCron extends AbstractCronTask
{
    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
        //return '@daily';
        return '*/1 * * * *';
    }
    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
        return 'Bet';
    }

    static function run(\swoole_server $server, int $taskId, int $fromWorkerId, $flags = null)
    {
        $tables = ['siam_csgobet','siam_dotabet','siam_lolbet'];
        $path = [UrlEnums::CSGO_BET_PATH,UrlEnums::DOTA_BET_PATH,UrlEnums::LOL_BET_PATH];
        $matchTables = ['siam_csgomatchs','siam_dotamatchs','siam_lolmatchs'];
        //获取所有比赛
        for ( $i=0;$i<count($path);$i++ ){
            MysqlPool::invoke(function (MysqlObject $db)use($tables,$path,$i,$matchTables){
                $match_ids = $db->where('status',2)->getColumn($matchTables[$i],'match_id');
                foreach ( $match_ids as $match_id ){
                    $matchBet = $db->where('match_id',$match_id)->count($tables[$i]);
                    if( !$matchBet ){
                        list($s1, $s2) = explode(' ', microtime());
                        $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
                        $url = UrlEnums::FJURL.$path[$i]."?match_id={$match_id}&version=2";
                        $client = new HttpClient($url);
                        $option = [
                            'path'      => $path[$i],
                            'api_time'  => $microtime
                        ];
                        $header = Auth::getInstance()->header($option);
                        $client->setHeaders($header,true,false);
                        $response = $client->get();
                        $content = $response->getBody();
                        $data = json_decode($content,true);
                        if( isset($data['code']) && $data['code'] == 200 && $data['data'] ){
                            foreach ( $data['data'] as $k=>$v ){
                                $v['options'] = json_encode($v['options']);
                                $res = $db->where('bet_id',$v['bet_id'])->getOne($tables[$i]);
                                if( !$res ){
                                    $raw = $db->insert($tables[$i],$v);
                                }
                            }
                        }
                    }
                }
            });
        }
    }
}